#!/bin/bash

# HDC端口扫描器 - 依赖检查和安装脚本
# 适用于macOS系统

# 获取脚本所在目录的绝对路径
# 使用兼容的方法确保获取真实的绝对路径，避免符号链接问题
get_script_dir() {
    local source="${BASH_SOURCE[0]}"
    # 解析符号链接
    while [[ -L "$source" ]]; do
        local dir="$(cd -P "$(dirname "$source")" && pwd)"
        source="$(readlink "$source")"
        [[ $source != /* ]] && source="$dir/$source"
    done
    cd -P "$(dirname "$source")" && pwd
}

SCRIPT_DIR="$(get_script_dir)"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

print_msg() {
    echo -e "${1}${2}${NC}"
}

print_header() {
    echo ""
    print_msg $BLUE "═══════════════════════════════════════"
    print_msg $BLUE "$1"
    print_msg $BLUE "═══════════════════════════════════════"
}

check_command() {
    local cmd=$1
    local name=$2
    
    if command -v "$cmd" >/dev/null 2>&1; then
        print_msg $GREEN "✅ $name 已安装"
        return 0
    else
        print_msg $RED "❌ $name 未安装"
        return 1
    fi
}

install_homebrew() {
    if ! command -v brew >/dev/null 2>&1; then
        print_msg $YELLOW "安装 Homebrew..."
        /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
        
        # 添加到PATH
        if [[ -f "/opt/homebrew/bin/brew" ]]; then
            echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zprofile
            eval "$(/opt/homebrew/bin/brew shellenv)"
        fi
    else
        print_msg $GREEN "✅ Homebrew 已安装"
    fi
}

install_dependencies() {
    print_msg $YELLOW "更新 Homebrew..."
    brew update
    
    print_msg $YELLOW "安装依赖包..."
    
    # 安装netcat
    if ! check_command nc "netcat"; then
        print_msg $YELLOW "安装 netcat..."
        brew install netcat
    fi
    
    # 安装coreutils
    if ! check_command timeout "timeout"; then
        print_msg $YELLOW "安装 coreutils..."
        brew install coreutils
    fi
    
    # 检查flock (通常随系统提供)
    if ! check_command flock "flock"; then
        print_msg $YELLOW "尝试安装 flock..."
        brew install flock 2>/dev/null || {
            print_msg $YELLOW "注意: flock 可能需要手动安装"
        }
    fi
}

check_hdc() {
    if check_command hdc "HDC"; then
        local version
        version=$(hdc version 2>/dev/null | head -1)
        print_msg $GREEN "   版本: $version"
        return 0
    else
        print_msg $YELLOW "HDC 未安装或不在 PATH 中"
        print_msg $YELLOW "请按以下步骤安装:"
        print_msg $YELLOW "1. 访问 HarmonyOS 开发者官网"
        print_msg $YELLOW "2. 下载 Command Line Tools 或 DevEco Studio"
        print_msg $YELLOW "3. 将 hdc 可执行文件添加到 PATH"
        print_msg $YELLOW ""
        print_msg $YELLOW "或者创建软链接:"
        print_msg $YELLOW "sudo ln -s /path/to/hdc /usr/local/bin/hdc"
        return 1
    fi
}

setup_environment() {
    # 检查并设置shell配置
    local shell_rc=""
    case "$SHELL" in
        */zsh)
            shell_rc="$HOME/.zshrc"
            ;;
        */bash)
            shell_rc="$HOME/.bash_profile"
            ;;
        *)
            shell_rc="$HOME/.profile"
            ;;
    esac
    
    print_msg $BLUE "当前Shell: $SHELL"
    print_msg $BLUE "配置文件: $shell_rc"
    
    # 检查PATH设置
    if [[ -f "/opt/homebrew/bin/brew" ]] && ! echo "$PATH" | grep -q "/opt/homebrew/bin"; then
        print_msg $YELLOW "添加 Homebrew 到 PATH..."
        echo '' >> "$shell_rc"
        echo '# Homebrew' >> "$shell_rc"
        echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> "$shell_rc"
        print_msg $GREEN "已添加到 $shell_rc"
        print_msg $YELLOW "请运行: source $shell_rc"
    fi
}

test_installation() {
    print_header "测试安装"
    
    local all_ok=true
    
    # 测试基本命令
    check_command nc "netcat" || all_ok=false
    check_command timeout "timeout" || all_ok=false
    check_command ping "ping" || all_ok=false
    check_hdc || all_ok=false
    
    if $all_ok; then
        print_msg $GREEN ""
        print_msg $GREEN "🎉 所有依赖都已正确安装！"
        print_msg $GREEN "现在可以运行端口扫描器了："
        print_msg $YELLOW "./port_scanner.sh    # HDC端口扫描器"
        print_msg $YELLOW "./start.sh          # 快速启动菜单"
    else
        print_msg $RED ""
        print_msg $RED "❌ 部分依赖缺失，请检查上述输出"
    fi
}

show_help() {
    print_header "HDC端口扫描器 - 环境设置"
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  -h, --help     显示此帮助信息"
    echo "  -c, --check    仅检查依赖，不安装"
    echo "  -i, --install  安装所有依赖"
    echo "  -t, --test     测试安装结果"
    echo ""
    echo "默认行为: 检查并安装缺失的依赖"
}

main() {
    local action="install"
    
    # 解析命令行参数
    while [[ $# -gt 0 ]]; do
        case $1 in
            -h|--help)
                show_help
                exit 0
                ;;
            -c|--check)
                action="check"
                shift
                ;;
            -i|--install)
                action="install"
                shift
                ;;
            -t|--test)
                action="test"
                shift
                ;;
            *)
                print_msg $RED "未知选项: $1"
                show_help
                exit 1
                ;;
        esac
    done
    
    print_header "HDC端口扫描器 - 环境设置"
    
    case $action in
        check)
            print_header "检查依赖"
            check_command brew "Homebrew"
            check_command nc "netcat"
            check_command timeout "timeout"
            check_command ping "ping"
            check_hdc
            ;;
        install)
            print_header "安装依赖"
            
            # 检查操作系统
            if [[ "$(uname)" != "Darwin" ]]; then
                print_msg $RED "此脚本仅适用于 macOS 系统"
                exit 1
            fi
            
            # 安装Homebrew
            install_homebrew
            
            # 安装依赖
            install_dependencies
            
            # 设置环境
            setup_environment
            
            # 测试安装
            test_installation
            ;;
        test)
            test_installation
            ;;
    esac
}

main "$@"